package com.avertymaroc.users;

import static com.avertymaroc.library.C.ERREUR_FORM;
import static com.avertymaroc.library.C.EXISTE_DEJA;
import static com.avertymaroc.library.C.EXTRA;
import static com.avertymaroc.library.C.NON_ACTIVE;
import static com.avertymaroc.library.C.TAG_ANNEE;
import static com.avertymaroc.library.C.TAG_EMAIL;
import static com.avertymaroc.library.C.TAG_ERRORS;
import static com.avertymaroc.library.C.TAG_ETAT;
import static com.avertymaroc.library.C.TAG_INFOS;
import static com.avertymaroc.library.C.TAG_PASSE;
import static com.avertymaroc.library.C.TAG_PRENOM;
import static com.avertymaroc.library.C.TAG_PROFESSION;
import static com.avertymaroc.library.C.TAG_SEXE;
import static com.avertymaroc.library.C.TAG_SUCCESS;
import static com.avertymaroc.library.C.TAG_VILLE;
import static com.avertymaroc.library.C.VALIDE;
import static com.avertymaroc.library.C.site_url;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.avertymaroc.app.MainActivity;
import com.avertymaroc.app.R;
import com.avertymaroc.library.AlertDialogue;
import com.avertymaroc.library.HttpManager;
import com.avertymaroc.library.Utils;

public class Inscription extends SherlockFragmentActivity {

	private static final int NUM_ITEMS = 4;
	private MyAdapter mAdapter;
	private ViewPager mPager;
	static JSONObject user = null;
	static boolean email_valide = false;

	private static Button next, prev;

	static private EditText email = null;
	static private EditText prenom = null;
	static private EditText mdp = null;
	static private EditText confirmer = null;
	static private RadioGroup sexe = null;
	static private Spinner annee = null;
	static private Spinner ville = null;
	static private Spinner profession = null;
	static private CheckBox accepte_terme = null;

	// Les champ de l'inscription

	private String insc_email;
	private String insc_prenom;
	private String insc_mdp;
	private int insc_ville;
	private int insc_sexe;
	private int insc_profession;
	private int insc_annee;
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(MainActivity.THEME);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inscription);
		
		mAdapter = new MyAdapter(getSupportFragmentManager());
		mPager = (ViewPager) findViewById(R.id.pager_inscription);
		mPager.setAdapter(mAdapter);
		Listener listen = new Listener();

		next = (Button) findViewById(R.id.btn_next);
		prev = (Button) findViewById(R.id.btn_prev);
		prev.setVisibility(Button.INVISIBLE);
		mPager.setOnPageChangeListener(listen);

		next.setOnClickListener(listen);
		prev.setOnClickListener(listen);
		
		//	Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();

	}

	public static class MyAdapter extends FragmentPagerAdapter {
		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return NUM_ITEMS;
		}

		@Override
		public Fragment getItem(int position) {
			return ArrayListFragment.newInstance(position);
		}
	}

	public static class ArrayListFragment extends Fragment {
		public int mNum;

		/**
		 * Create a new instance of CountingFragment, providing "num" as an
		 * argument.
		 */
		static ArrayListFragment newInstance(int num) {
			ArrayListFragment f = new ArrayListFragment();

			// Supply num input as an argument.
			Bundle args = new Bundle();
			args.putInt("num", num);
			f.setArguments(args);
			return f;
		}

		/**
		 * When creating, retrieve this instance's number from its arguments.
		 */
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			mNum = getArguments() != null ? getArguments().getInt("num") : 1;
		}

		/**
		 * The Fragment's UI is just a simple text view showing its instance
		 * number.
		 */
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View v;

			switch (mNum) {
			case 0:
				v = inflater.inflate(R.layout.insc_etape1, container, false);
				email = (EditText) v.findViewById(R.id.insc_email);
				
				break;
			case 1:
				v = inflater.inflate(R.layout.insc_etape2, container, false);
				sexe = (RadioGroup) v.findViewById(R.id.sexe);
				prenom = (EditText) v.findViewById(R.id.prenom);
				mdp = (EditText) v.findViewById(R.id.mdp);
				confirmer = (EditText) v.findViewById(R.id.confirmer_mdp);
				
				if(user != null){
					try {
						String txt = user.toString();
						Toast.makeText(getActivity(), txt, 3000).show();
						if(user.getInt(TAG_SEXE) == 1)
							((RadioButton)v.findViewById(R.id.sexe_homme)).setSelected(true);
						else if(user.getInt(TAG_SEXE) == 2)
							((RadioButton)v.findViewById(R.id.sexe_femme)).setSelected(true);
						prenom.setText(user.getString(TAG_PRENOM));
						
					} catch (JSONException e) {
						Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
						}
					
					
				}

				break;
			case 2:
				v = inflater.inflate(R.layout.insc_etape3, container, false);

				annee = (Spinner) v.findViewById(R.id.annee);
				ville = (Spinner) v.findViewById(R.id.ville);
				profession = (Spinner) v.findViewById(R.id.profession);

				List<String> anne = new ArrayList<String>();

				// initialisation de l anne
				int current_year = Calendar.getInstance().get(Calendar.YEAR);
				for (int i = current_year - 14; i > current_year - 94; i--)
					anne.add("" + i);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						getActivity(), android.R.layout.simple_spinner_item,
						anne);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				annee.setAdapter(adapter);				
				// dans le cas  d'un mail extra on remplit les champ 
				if(user != null){
					try {
						ville.setSelection(user.getInt(TAG_VILLE)  , true);
						annee.setSelection(user.getInt(TAG_ANNEE) - (current_year - 14 ), true);
						profession.setSelection(user.getInt(TAG_PROFESSION) + 1, true);
						
					} catch (JSONException e) {
						Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
					}	
				}
				break;
			case 3:
				v = inflater.inflate(R.layout.insc_etape4, container, false);
				accepte_terme = (CheckBox) v.findViewById(R.id.accepter_termes);
				break;
			default:
				v = inflater.inflate(R.layout.insc_etape1, container, false);
				break;
			}

			
			
			return v;
		}

	}

	private class Listener implements OnPageChangeListener, OnClickListener {

		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.btn_next:

				if (mPager.getCurrentItem() == 0)
					validation_email(email.getText().toString());
				else
					try {

						validation_etape(mPager.getCurrentItem());
						if (mPager.getCurrentItem() == 3) {
							inscrire_user();
						} else
							nextStep();

					} catch (Exception e) {
						AlertDialogue.afficher(Inscription.this,
								e.getMessage(), stringRes(R.string.erreur),
								stringRes(R.string.btn_ok));
					}

				break;

			case R.id.btn_prev:
				if (mPager.getCurrentItem() == 1)
					email_valide = false;
				prevtStep();
				break;
			default:
				break;
			}

		}

		@Override
		public void onPageScrollStateChanged(int state) {

		}

		@Override
		public void onPageScrolled(int position, float offset, int offestPxle) {

		}

		@Override
		public void onPageSelected(int pageIndex) {
			if (pageIndex == 0) {
				prev.setVisibility(Button.INVISIBLE);
				email_valide = false;
			} else {
				prev.setVisibility(Button.VISIBLE);
				if (pageIndex == 1 && !email_valide)
					mPager.setCurrentItem(0);

			}

		}

	}

	@Override
	public void onBackPressed() {

		new AlertDialog.Builder(Inscription.this)
				.setTitle(R.string.mot_alerte)
				.setMessage(R.string.alert_quite)
				.setPositiveButton(R.string.mot_quitter,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Inscription.super.onBackPressed();

							}

						})
				.setNegativeButton(R.string.btn_annuler,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();

							}
						}).create().show();

	}

	private String stringRes(int resId) {
		return getResources().getString(resId);
	}

	private void validation_email(String mail) {

		if (mail.trim().length() == 0) {

			Toast.makeText(getApplicationContext(),
					"l'adresse email ne peut pas etre vide", Toast.LENGTH_SHORT)
					.show();
		} else if (!Utils.isValidEmailAddress(mail)) {
			Toast.makeText(getApplicationContext(),
					stringRes(R.string.err_email_inalide), Toast.LENGTH_SHORT)
					.show();
		} else {

			
			HttpManager valid_email = new HttpManager(Inscription.this) {

				@Override
				protected void onPostExecute(String file_url) {

					try {
						this.getpDialog().dismiss();
						JSONObject resultat = this.getResult();
						int etat = resultat.getInt(TAG_ETAT);
						switch (etat) {
						case NON_ACTIVE:
							AlertDialogue.afficher(Inscription.this,
									R.string.email_non_active,
									R.string.email_non_active_titre,
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,int which) {
											resend_activation_mail(email.getText().toString());
										}
									}, R.string.btn_renvoie_mail,
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,int which) {
										dialog.dismiss();
										}
									}, R.string.btn_annuler);
							break;

						case EXISTE_DEJA:

							AlertDialogue.afficher(Inscription.this,
									stringRes(R.string.email_existe),
									stringRes(R.string.email_existe_titre),
									stringRes(R.string.btn_ok));
							break;

						case EXTRA:
							
							email_valide = true;
							user = resultat.getJSONObject(TAG_INFOS);
							insc_email = email.getText().toString();
							
							nextStep();
							break;
						case VALIDE:
							email_valide = true;
							insc_email = email.getText().toString();
							nextStep();

							break;

						case ERREUR_FORM :
							AlertDialogue.afficher(Inscription.this,
									stringRes(R.string.form_erreur),
									stringRes(R.string.erreur),
									stringRes(R.string.btn_ok));
							break;

						}
					} catch (JSONException e) {

					}

				}
			};

			Map<String, String> params = new HashMap<String, String>();
			params.put(TAG_EMAIL, mail);

			valid_email.setUrl(site_url("mobile/users/index"))
					.setParams(params).setContext(Inscription.this)
					.setMethode("POST").execute();
		}
	}

	private void validation_etape(int etape) throws Exception {

		switch (etape) {
		case 1:
			insc_sexe = sexe.getCheckedRadioButtonId();
			insc_prenom = prenom.getText().toString();
			insc_mdp = mdp.getText().toString();
			insc_mdp = insc_mdp.trim();

			if (insc_sexe == -1)
				throw new Exception(stringRes(R.string.err_sexe_non_selected));
			else
				insc_sexe = (insc_sexe == R.id.sexe_homme)?1:2;

			if (insc_prenom.trim().length() < 3)
				throw new Exception(stringRes(R.string.err_prenom_invalide));

			if (insc_mdp.length() < 6)
				throw new Exception(stringRes(R.string.err_pass_court));

			if (!insc_mdp.equals(confirmer.getText().toString().trim()))
				throw new Exception(stringRes(R.string.err_mdp_non_identique));

			break;

		case 2:
			if (annee.getSelectedItem() != null) {
				insc_annee = Integer.parseInt((String) annee.getSelectedItem());
			} else {
				throw new Exception(stringRes(R.string.err_anne_non_selected));
			}

			if (ville.getSelectedItemPosition() != AdapterView.INVALID_POSITION) {
				insc_ville = ville.getSelectedItemPosition() + 1;
			} else {
				throw new Exception(stringRes(R.string.err_ville_non_selected));
			}

			if (profession.getSelectedItemPosition() != AdapterView.INVALID_POSITION) {
				insc_profession = profession.getSelectedItemPosition() + 1;
			} else {
				throw new Exception(
						stringRes(R.string.err_profession_non_selected));
			}

			break;
		case 3:
			if (!accepte_terme.isChecked())
				throw new Exception(stringRes(R.string.err_non_accepte_terme));
			break;
		}
	}

	private void nextStep() {
		if (mPager.getCurrentItem() + 1 < NUM_ITEMS)
			mPager.setCurrentItem(mPager.getCurrentItem() + 1);
	}

	private void prevtStep() {
		if (mPager.getCurrentItem() > 0)
			mPager.setCurrentItem(mPager.getCurrentItem() - 1);
	}

	private void inscrire_user() {
		Map<String, String> params = new HashMap<String, String>();

		params.put(TAG_EMAIL, insc_email);
		params.put(TAG_SEXE, insc_sexe + "");
		params.put(TAG_PRENOM, insc_prenom);
		params.put(TAG_PASSE, insc_mdp);
		params.put(TAG_ANNEE, insc_annee + "");
		params.put(TAG_VILLE, insc_ville + "");
		params.put(TAG_PROFESSION, insc_profession + "");

		HttpManager inscrire = new HttpManager(Inscription.this) {

			@Override
			protected void onPostExecute(String file_url) {
				this.getpDialog().dismiss();
				JSONObject res = this.getResult();
				try {

					int succes = res.getInt(TAG_SUCCESS);

					if (succes == 0) {
						String erreurs = res.getString(TAG_ERRORS);

						AlertDialogue.afficher(Inscription.this, erreurs,
								stringRes(R.string.erreur),
								new DialogInterface.OnClickListener() {
									// premiere boutton
									@Override
									public void onClick(DialogInterface dialog,
											int which) {

										dialog.dismiss();
										Intent i = Inscription.this.getIntent();
										finish();
										startActivity(i);

									}
								}, stringRes(R.string.mot_ressayer),

								new DialogInterface.OnClickListener() {
									// deuxiemme boutton
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
										finish();

									}
								}, stringRes(R.string.mot_quitter));

					} else if (succes == 1) {
						AlertDialogue.afficher(Inscription.this,
								stringRes(R.string.insc_succes),
								stringRes(R.string.insc_succes_titre),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
										Inscription.this.finish();
									}
								}, stringRes(R.string.btn_ok));
					}
				} catch (JSONException e) {
					finish();
				}

			}
		};
		inscrire.setUrl(site_url("mobile/users/creat")).setParams(params)
				.setMethode("POST").execute();
	}
	
	public  void resend_activation_mail(final String toMail){
		
		HttpManager resend = new HttpManager(Inscription.this) {

			protected void onPostExecute(String file_url) {				
				getpDialog().dismiss();
				JSONObject res = getResult();
				try {
					int success = res.getInt(TAG_SUCCESS);
					if(success == 1){
						AlertDialogue.afficher(Inscription.this, 
								R.string.alert_resend_succes,
								R.string.alert_resend_titre,R.string.btn_ok
								);
					}else{
						AlertDialogue.afficher(Inscription.this, 
								R.string.alert_resend_failer,
								R.string.alert_resend_titre,
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog, int which) {
										dialog.dismiss();
										resend_activation_mail(toMail);
									}
								},
								R.string.mot_ressayer,
								
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog, int which) {
										dialog.dismiss();
									}
								},
								R.string.btn_annuler
								);
					}
				} catch (JSONException e) {
					Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
				}
				
			}
		};
		Map<String, String> param = new HashMap<String, String>();
		param.put(TAG_EMAIL, toMail);
		
		resend.setParams(param)
			  .setUrl(site_url("mobile/users/resend_activation_mail"))
			  .execute();
		
	}
	
	

}
